package com.bihucms.ssm.controller.user;

import com.bihucms.ssm.model.User;
import com.bihucms.ssm.service.user.UserService;
import com.bihucms.ssm.util.BihuUtil;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户
 */
@Controller
@Scope("prototype")
@RequestMapping("/user")
public class UserController {
    private Logger log = Logger.getLogger(UserController.class);
    @Resource
    private UserService userService;

    /**
     * 跳转到登录页面的方法
     */
    @RequestMapping(value = "/login")
    public ModelAndView goLogin(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/user/login");
        return mv;
    }

    /**
     * 登录提交
     */
    @RequestMapping(value = "/toLogin")
    public ModelAndView toLogin(HttpServletRequest request){
        ModelAndView mv = new ModelAndView();
        Map returnMap = new HashMap();

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        Map map = new HashMap();
        map.put("username",username);
        map.put("password",password);
        Map<String, Object> aNull = BihuUtil.isNull(map);
        if(aNull.get("msg")==300){
            returnMap = BihuUtil.returnMap("300","用户名或者密码不能为空");
            mv.addObject(returnMap);
        }

        User user = new User();
        user.setUserName(username);
        user.setUserPassword(password);

        User returnUser = userService.toLogin(user);
        if(returnUser==null){
            mv.setViewName("/user/login");
            mv.addObject("desc","用户名和密码不匹配");
            mv.addObject("msg","300");
            return mv;
        }


        mv.setViewName("/user/index");
        mv.addObject("desc","");
        mv.addObject("msg","200");
        mv.addObject("user",returnUser);
        return mv;
    }

}
